import "./textfield.scss";
import { Search, Arrow } from "../svg/svg";
import classNames from "classnames";
import { useEffect, useRef, useState } from "react";
import { useAppDispatch } from "@/utils/hook";
import { useAppSelector } from "@/utils/hook";
import {
  setHistorySearchValue,
  setLocalStroageValue,
} from "@/store/counterSlice";
export type TextFieldProps = {
  label?: string | React.ReactNode;
  type: "text" | "select" | "password" | "search" | "checkbox";
  onChange?: (value: any) => void;
  error?: boolean;
  errorMessage?: string;
  placeholder?: string;
  onClick?: (e?: any) => any;
  // 接受一个参数
  onKeyup?: (e?: any) => any | void;
  onkeyDown?: (e?: any) => any | void;
  className?: string;
  id?: number;
  value?: string;
  color?: string;
};
export const TextField = ({
  label,
  type,
  onChange,
  error,
  errorMessage,
  placeholder,
  onKeyup,
  onkeyDown,
  className = "",
  value,
  color,
  id = 0,
  ...rest
}: TextFieldProps): React.ReactElement => {
  function handleChange(value: any) {
    onChange?.(value);
    setHistoryValue(value);
  }

  function textFieldClassName(type: string): string {
    return classNames(
      "dashboard_textfield",
      error ? "error" : "",
      className,
      type
    );
  }

  const textfieldRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    appDispatch(setLocalStroageValue(localStorage.search_history));
  }, [localStorage.search_history]);

  // 历史搜索信息
  const [historyValue, setHistoryValue] = useState<string | null>(null);

  // 设置历史搜索
  const { historySearchValue } = useAppSelector((state) => state.counter);
  const appDispatch = useAppDispatch();

  // 数据回显
  const itemClick = (item: string) => {
    if (textfieldRef.current) {
      textfieldRef.current.blur();
      onKeyup?.(item);
      textfieldRef.current.value = item;
    }
    setIsShow(false);
  };

  function handleKeyup(e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === "Enter" && textfieldRef.current?.value !== "") {
      onKeyup?.(textfieldRef.current?.value);
      appDispatch(setHistorySearchValue(historyValue as string));
    }
  }

  function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === "Enter") {
      console.log(111);
      onkeyDown?.();
    }
  }

  const [isShow, setIsShow] = useState(false);

  const ArrowClassName = (): string => {
    return classNames("dashboard_arrow", isShow && "arrow_bottom");
  };

  function setElement() {
    switch (type) {
      case "text":
        return (
          <>
            <div className={textFieldClassName(type)} {...rest}>
              {label && <span className="dashboard_label">{label}</span>}
              <label
                htmlFor={`text_dashboard_${id}`}
                data-error={errorMessage}
                className={classNames(error && "error")}
              >
                <input
                  type="text"
                  id={`text_dashboard_${id}`}
                  onChange={(e) => handleChange(e.target.value)}
                  placeholder={placeholder}
                  onKeyUp={(e) => handleKeyup(e)}
                  autoComplete="off"
                  value={value}
                  onKeyDown={handleKeyDown}
                />
              </label>
            </div>
          </>
        );
      case "password":
        return (
          <>
            <div className={textFieldClassName(type)} {...rest}>
              {label && <span className="dashboard_label">{label}</span>}
              <label
                htmlFor={`password_dashboard_${id}`}
                data-error={errorMessage}
                className={classNames(error && "error")}
              >
                <input
                  type="password"
                  id={`password_dashboard_${id}`}
                  onChange={(e) => handleChange(e.target.value)}
                  placeholder={placeholder}
                  onKeyUp={(e) => handleKeyup(e)}
                  autoComplete="off"
                  value={value}
                  onKeyDown={handleKeyDown}
                />
              </label>
            </div>
          </>
        );
      case "search":
        return (
          <>
            <div className={textFieldClassName(type)} {...rest}>
              {label && <span className="dashboard_label">{label}</span>}

              <label
                htmlFor={`search_dashboard_${id}`}
                data-error={errorMessage}
                className={classNames(error && "error")}
              >
                <input
                  type="text"
                  id={`search_dashboard_${id}`}
                  onChange={(e) => handleChange(e.target.value)}
                  placeholder={placeholder}
                  onKeyUp={(e) => handleKeyup(e)}
                  autoComplete="off"
                  value={value}
                  onKeyDown={handleKeyDown}
                />
                <i>
                  <Search color="black" className="dashboard_svg" />
                </i>
              </label>
            </div>
          </>
        );
      case "checkbox":
        return (
          <>
            <div className={textFieldClassName(type)} {...rest}>
              <label
                htmlFor={`checkbox_dashboard_${id}`}
                data-error={errorMessage}
                className="is_checkbox"
              >
                <input
                  type="checkbox"
                  id={`checkbox_dashboard_${id}`}
                  onChange={(e) => handleChange(e.target.value)}
                  placeholder={placeholder}
                  onKeyUp={(e) => handleKeyup(e)}
                />
                {label && (
                  <span
                    className="dashboard_label checkbox"
                    style={{ color: color }}
                  >
                    {label}
                  </span>
                )}
              </label>
            </div>
          </>
        );
      default:
        return (
          <>
            <div className={textFieldClassName(type)} {...rest}>
              {label && <span className="dashboard_label">{label}</span>}
              <label
                htmlFor={`select_dashboard_${id}`}
                data-error={errorMessage}
                className={classNames(error && "error")}
              >
                <input
                  type="text"
                  id={`select_dashboard_${id}`}
                  onChange={(e) => handleChange(e.target.value)}
                  onFocus={() => setIsShow(true)}
                  placeholder={placeholder}
                  onKeyUp={(e) => handleKeyup(e)}
                  autoComplete="off"
                  ref={textfieldRef}
                />
                <i>
                  <Arrow color="black" className={ArrowClassName()} />
                </i>
              </label>
              {historySearchValue && isShow && (
                <div className="dashboard_list">
                  <ul
                    className="dashboard_history_search_list"
                    onClick={() => setIsShow(false)}
                  >
                    {historySearchValue.map((item, key) => (
                      <li
                        className="dashboard_history_search_item"
                        key={key}
                        onClick={() => itemClick(item)}
                      >
                        {item}
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          </>
        );
    }
  }

  return <>{setElement()}</>;
};
